
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class 使用iterator {
    public static void main(String[] args) {
        ReverseList<String> rlist=new ReverseList<String>();
        rlist.add("apple");
        rlist.add("orange");
        rlist.add("pear");
        for(String s:rlist){
            System.out.println(s);
        }
    }
}
class ReverseList<T> implements Iterable<T>{
    private List<T> list=new ArrayList<>();
    public void add(T t){
        list.add(t);
    }
    @Override
    public Iterator<T> iterator(){
        return new ReverseIterator(list.size());
    }
    class ReverseIterator implements Iterator<T>{
        int index;
        ReverseIterator(int index){
            this.index=index;
        }
        @Override
        public boolean hasNext(){
            return index>0;
        }
        @Override
        public T next(){
            index--;
            //ReverseList.this获得当前外部类的this引用
            return ReverseList.this.list.get(index);
        }
    }
}